package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductPackLabelVO;
import com.wing.order.dao.OrderDeliveryLabelDao;
import com.wing.order.model.entity.OrderDeliveryLabel;
import com.wing.order.model.entity.OrderDeliverySign;
import com.wing.order.model.entity.OrderDeliverySignDetail;
import com.wing.order.model.request.OrderDeliveryLabelForm;
import com.wing.order.model.response.OrderDeliveryLabelVO;
import com.wing.product.model.request.ProductPackLabelForm;
import com.wing.product.service.ProductPackLabelService;
import com.wing.warehouse.model.response.PalletBoxListVO;
import com.wing.warehouse.service.PalletBoxListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 签收单扫描的包装条码-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class OrderDeliveryLabelServiceImpl extends ServiceImpl<OrderDeliveryLabelDao, OrderDeliveryLabel> implements OrderDeliveryLabelService {

    @Qualifier("com.wing.enterprise.feign.EnterpriseClient")
    @Autowired
    private EnterpriseClient enterpriseClient;

    @Autowired DynamicService dynamicService;

    @Autowired
    private OrderDeliverySignService deliverySignService;

    @Autowired
    private OrderDeliverySignDetailService deliverySignDetailService;

    @Autowired
    private InventoryInoutJobService inventoryInoutJobService;

    @Autowired
    private PalletBoxListService boxListService;

    @Autowired
    private ProductPackLabelService productPackLabelService;



    @Override
    public int add(OrderDeliveryLabelForm orderDeliveryLabelForm) {

        //校验

        OrderDeliveryLabel orderDeliveryLabel =new OrderDeliveryLabel();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OrderDeliveryLabel.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderDeliveryLabelForm, orderDeliveryLabel, copyOptions);

        return baseMapper.insert(orderDeliveryLabel);
    }

    @Override
    public List<OrderDeliveryLabelVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<OrderDeliveryLabelVO> pageList4app(Page page, Map<String, Object> params) {
        List<OrderDeliveryLabelVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public OrderDeliveryLabelVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public JsonResult<ProductPackLabelVO> getPackLabel(Long signId, String labelCode) {

        JsonResult<ProductPackLabelVO> jsonResult=enterpriseClient.getProductPackLabelVOList(labelCode,0);
        ProductPackLabelVO labels=jsonResult.getData();
        if (Result.Code.FAIL.getCode()==jsonResult.getCode()){
            return jsonResult;
        }
        if (labels==null){
            return JsonResult.fail("未找到包装条码数据");
        }
        if (signId!=null){
            List<OrderDeliveryLabelVO> deliveryDetailVO=baseMapper.getDeliveryLabel(signId,labelCode,null,null,null);
            if (deliveryDetailVO.size()==0){
                return JsonResult.fail("未找到配送业务明细的条码数据");
            }

//            if (!labels.get(0).getSkuCode().equals(deliveryDetailVO.getSkuCode())){
//                return JsonResult.fail("此包装编码的产品SKU["+labels.get(0).getSkuCode()+"]不属于该产品SKU["+deliveryDetailVO.getSkuCode()+"]");
//            }
            labels.setSignId(deliveryDetailVO.get(0).getSignId());
            labels.setSignDetailId(deliveryDetailVO.get(0).getSignDetailId());
            labels.setDeliveryLabelId(deliveryDetailVO.get(0).getId());
            labels.setSkuPic(deliveryDetailVO.get(0).getSkuPic());
            labels.setSkuName(deliveryDetailVO.get(0).getSkuName());
            labels.setSkuName(deliveryDetailVO.get(0).getSkuName());
            labels.setSkuSpec(deliveryDetailVO.get(0).getSkuSpec());
            labels.setMarketPrice(deliveryDetailVO.get(0).getMarketPrice());
            labels.setProductTypeName(deliveryDetailVO.get(0).getProductTypeName());
            labels.setProductCategoryName(deliveryDetailVO.get(0).getProductCategoryName());
            labels.setProductBrandName(deliveryDetailVO.get(0).getProductBrandName());
            labels.setUnitName(deliveryDetailVO.get(0).getUnitName());
            if (OrderDeliveryLabel.Status.inventoryIn.equals(deliveryDetailVO.get(0).getStatus())){
                return JsonResult.fail("此包装条码入库");
            }
            return JsonResult.success(labels);
        }

        return JsonResult.fail("获取包装条码失败");
    }

    @Override
    public List<OrderDeliveryLabelVO> getDeliveryLabel(Long signId,Long boxId,String queryFlag) {
        return baseMapper.getDeliveryLabel(signId,null,boxId,queryFlag,null);
    }

    @Override
    public List<OrderDeliveryLabelVO> getDeliveryLabel(Long signId, Long boxId, String queryFlag, Long signDetailId) {
        return baseMapper.getDeliveryLabel(signId,null,boxId,queryFlag,signDetailId);
    }

    @Override
    @Transactional
    public void inventoryInSubmit(List<OrderDeliveryLabel> list) {

        List<OrderDeliveryLabelVO> listIn=new ArrayList<>();

        for (OrderDeliveryLabel orderDeliveryLabel:list){

//            List<OrderDeliveryLabel> orderReceiveLabels=orderDeliveryLabelService.list(new QueryWrapper<OrderDeliveryLabel>().eq("delivery_detail_id",orderDeliveryLabel.getDeliveryDetailId()).eq("pack_label_code",orderDeliveryLabel.getPackLabelCode()));
            OrderDeliveryLabelVO orderDeliveryLabelDb=baseMapper.get4appById(orderDeliveryLabel.getId());
            if (orderDeliveryLabelDb==null){
                throw new BusinessException("未找到包装条码");
            }
//            if (signId!=null&&signId.equals(orderDeliveryLabelDb.getSignId())){
//                throw new BusinessException("条码不在一个签收单明细里面");
//            }
            Long signId=orderDeliveryLabelDb.getSignId();


            if (OrderDeliveryLabel.Status.inventoryIn.equals(orderDeliveryLabelDb.getStatus())){
                throw new BusinessException("此包装条码已入库");
            }

            if (orderDeliveryLabel.getQuantity()>orderDeliveryLabelDb.getPackLabelQuantity()){
                throw new BusinessException("入库数量不能大于签收数量");
            }
            PalletBoxListVO palletBoxListVO=boxListService.get4appById(orderDeliveryLabel.getBoxId());
            if (palletBoxListVO.getWarehouseId()==null){
                throw new BusinessException("料箱未绑定库位");
            }
            ProductPackLabelForm productPackLabelForm=productPackLabelService.extractLabel4InventoryIn(orderDeliveryLabelDb.getPackLabelCode(),orderDeliveryLabel.getQuantity().intValue(),1,palletBoxListVO.getBoxId(),palletBoxListVO.getWarehouseId(),palletBoxListVO.getAreaId(),palletBoxListVO.getShelfId(),palletBoxListVO.getSpaceId());
//            if (JsonResult.Code.SUCCESS.getCode()==jsonResult.getCode()){
                if (!orderDeliveryLabelDb.getQuantity().equals(orderDeliveryLabel.getQuantity())){
//                    ProductPackLabelForm productPackLabelForm=jsonResult.getData();
                    OrderDeliveryLabel orderDeliveryLabel1=new OrderDeliveryLabel();
                    BeanUtils.copyProperties(orderDeliveryLabelDb,orderDeliveryLabel1);
                    orderDeliveryLabel1.setId(null);
                    orderDeliveryLabel1.setPackLabelCode(productPackLabelForm.getCode());
                    orderDeliveryLabel1.setPackLabelId(productPackLabelForm.getId());
                    orderDeliveryLabel1.setQuantity(orderDeliveryLabelDb.getQuantity()-orderDeliveryLabel.getQuantity());
                    orderDeliveryLabel1.setPackLabelQuantity(orderDeliveryLabelDb.getQuantity()-orderDeliveryLabel.getQuantity());
                    baseMapper.insert(orderDeliveryLabel1);
                }
//            }else{
//                throw new BusinessException(jsonResult.getMsg());
//            }
            orderDeliveryLabelDb.setQuantityInOut(orderDeliveryLabel.getQuantity().intValue());
//            listIn.add(orderDeliveryLabelDb);
            OrderDeliveryLabel orderDeliveryLabel4Update=new OrderDeliveryLabel();

            if (palletBoxListVO!=null){
                orderDeliveryLabel4Update.setWarehouseId(palletBoxListVO.getWarehouseId());
                orderDeliveryLabel4Update.setAreaId(palletBoxListVO.getAreaId());
                orderDeliveryLabel4Update.setShelfId(palletBoxListVO.getShelfId());
                orderDeliveryLabel4Update.setSpaceId(palletBoxListVO.getSpaceId());
                orderDeliveryLabel4Update.setBoxId(orderDeliveryLabel.getBoxId());
                orderDeliveryLabelDb.setWarehouseId(palletBoxListVO.getWarehouseId());
                orderDeliveryLabelDb.setAreaId(palletBoxListVO.getAreaId());
                orderDeliveryLabelDb.setShelfId(palletBoxListVO.getShelfId());
                orderDeliveryLabelDb.setSpaceId(palletBoxListVO.getSpaceId());
                orderDeliveryLabelDb.setBoxId(orderDeliveryLabel.getBoxId());
            }
            listIn.add(orderDeliveryLabelDb);
            orderDeliveryLabel4Update.setId(orderDeliveryLabelDb.getId());
            //入库数
            orderDeliveryLabel4Update.setStorageQuantity(orderDeliveryLabel.getQuantity());
            orderDeliveryLabel4Update.setQuantity(orderDeliveryLabel.getQuantity());
            orderDeliveryLabel4Update.setPackLabelQuantity(orderDeliveryLabel.getQuantity());
            orderDeliveryLabel4Update.setStatus(OrderDeliveryLabel.Status.inventoryIn);
            baseMapper.updateById(orderDeliveryLabel4Update);

            int count=baseMapper.countNotFinish(orderDeliveryLabelDb.getSignDetailId());
            if (count==0){
                OrderDeliverySignDetail orderDeliverySignDetail=new OrderDeliverySignDetail();
                orderDeliverySignDetail.setId(orderDeliveryLabelDb.getSignDetailId());
                orderDeliverySignDetail.setStatus(OrderDeliverySignDetail.Status.inventoryIn);
                deliverySignDetailService.updateById(orderDeliverySignDetail);
            }

            count=deliverySignService.countNotFinish(signId);
            if (count==0){
                OrderDeliverySign orderDeliverySign=new OrderDeliverySign();
                orderDeliverySign.setId(signId);
                orderDeliverySign.setStatus(OrderDeliverySign.Status.inventoryIn);
                deliverySignService.updateById(orderDeliverySign);
            }
        }
        inventoryInoutJobService.inventoryIn(listIn);

    }

    @Override
    public List<PalletBoxListVO> getBoxBySignId(Long signId,Long signDetailId) {
        return baseMapper.getBoxBySignId(signId,signDetailId);
    }

}
